<template>
  <Card dis-hover :bordered="false">
    <Form inline :label-width="0" @submit.native.prevent>
      <Row>
        <Col span="22">
          <FormItem>
            <Input
              v-width="200"
              placeholder="请输入手机号或名称"
              v-model="params.keywords"
              @on-clear="searchData"
              @on-enter="searchData"
              clearable
            />
          </FormItem>
          <FormItem>
            <Select
              placeholder="请选择项目"
              v-width="120"
              v-model="params.project_id"
              :filterable="projectlist.length >= 10"
              @on-open-change="showAll"
              @on-change="searchData"
              clearable
            >
              <Option
                v-for="item in projectlist"
                :value="item.value"
                :key="item.value"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
          <FormItem>
            <TreeSelect
              v-width="150"
              placeholder="部门"
              v-model="params.department_id"
              :data="departmentList"
              @on-change="searchData"
              @on-clear="clearDep"
              clearable
            />
          </FormItem>
          <FormItem>
            <Select
              v-width="120"
              placeholder="请选择使用人"
              v-model="params.use_mid"
              @on-open-change="showAll"
              :filterable="userlist.length >= 10"
              @on-change="searchData"
              clearable
            >
              <Option
                v-for="item in userlist"
                :value="item.value"
                :key="item.value"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
          <FormItem>
            <Select
              placeholder="请选择使状态"
              v-width="120"
              v-model="params.status"
              @on-change="searchData"
              @on-clear="searchData"
              clearable
            >
              <Option
                v-for="item in statelist"
                :value="item.value"
                :key="item.value"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
        </Col>
        <Col span="2" style="text-align: right">
          <Button
            type="primary"
            @click="handleAdd"
            class="ivu-ml-8"
            v-hasC="{
              name: 'v1-buss-devices-update-devices',
              flag: 'v1/buss/devices/update-devices',
            }"
            >新增</Button
          >
        </Col>
      </Row>
    </Form>
    <Table
      :columns="columns"
      :data="list"
      :loading="loading"
      :max-height="tableHeigth"
    >
      <template #action="{ row }">
        <a
          @click="handleEdit(row)"
          v-hasC="{
            name: 'v1-buss-devices-update-devices2',
            flag: 'v1/buss/devices/update-devices',
          }"
          >编辑</a
        >
        <Divider
          type="vertical"
          v-hasC="{
            name: 'v1-buss-devices-update-devices2',
            flag: 'v1/buss/devices/update-devices',
          }"
        />
        <a
          @click="handleDel(row)"
          class="del"
          v-hasC="{
            name: 'v1-buss-devices-delete-devices',
            flag: 'v1/buss/devices/delete-devices',
          }"
          >删除</a
        >
      </template>
      <template #status_name="{ row }">
        <Badge
          status="success"
          :text="row.status_name"
          v-if="row.status_name === '正常'"
        />
        <Badge status="error" :text="row.status_name" v-else />
      </template>
      <template #sim_card="{ row }">
        <p v-for="item in row.sim_card" :key="item">
          {{ item }}
        </p>
      </template>
    </Table>
    <Page
      class="ivu-mt-16"
      :total="total"
      :modelValue="params.current"
      :page-size="params.size"
      :page-size-opts="pageOpts"
      show-total
      show-sizer
      @on-change="changePage"
      @on-page-size-change="changepageSize"
    />
    <Modal
      :mask-closable="false"
      v-model="addModal"
      :title="edit ? '新增' : '编辑'"
      :footer-hide="true"
      :draggable="true"
    >
      <Form
        ref="create"
        :model="equipmentInfo"
        :rules="rules"
        :label-width="80"
      >
        <FormItem label="手机型号" prop="phone_model" required>
          <Input
            v-model="equipmentInfo.phone_model"
            placeholder="请输入手机型号"
            :maxlength="30"
          />
        </FormItem>
        <FormItem label="名称" prop="name" required>
          <Input
            v-model="equipmentInfo.name"
            placeholder="请输入名称"
            :maxlength="30"
          />
        </FormItem>
        <FormItem label="部门" prop="department_id" required>
          <TreeSelect
            style="width: 100%"
            placeholder="请选择部门"
            v-model="equipmentInfo.department_id"
            :data="departmentAddList"
            @on-change="changeAddPro"
          />
        </FormItem>
        <FormItem label="项目" prop="project_id" required>
          <Select
            v-model="equipmentInfo.project_id"
            placeholder="请选择项目"
            @on-open-change="showAll"
            :filterable="projectlist.length >= 10"
            @on-change="changeAddPro"
          >
            <Option
              v-for="item in projectAddList"
              :value="item.value"
              :key="item.value"
              >{{ item.label }}</Option
            >
          </Select>
        </FormItem>

        <FormItem label="手机号" prop="mobile">
          <Select
            v-model="equipmentInfo.mobile"
            placeholder="请选择手机号"
            multiple
            @on-change="spaceSelect"
            :filterable="mobileAddList.length >= 10"
          >
            <Option
              v-for="item in mobileAddList"
              :value="item.value"
              :key="item.value"
              >{{ item.label }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="使用人" prop="use_mid" v-if="addUserlist.length > 0">
          <Select
            v-model="equipmentInfo.use_mid"
            placeholder="请选择使用人"
            @on-open-change="showAll"
            :filterable="addUserlist.length >= 10"
            label-in-value
            @on-change="changeAddUser"
            clearable
          >
            <Option
              v-for="item in addUserlist"
              :value="item.value"
              :key="item.value"
              >{{ item.label }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="备注" prop="remark">
          <Input
            v-model="equipmentInfo.remark"
            type="textarea"
            placeholder="请输入备注"
            :rows="4"
          />
        </FormItem>
        <FormItem label="状态" prop="status">
          <Switch v-model="equipmentInfo.status" />
        </FormItem>
      </Form>
      <div slot="footer" style="text-align: right">
        <Button type="default" @click="addModal = false">取消</Button>
        <Button
          type="primary"
          @click="ok"
          :loading="btnLoading"
          style="margin-left: 10px"
          >保存</Button
        >
      </div>
    </Modal>
  </Card>
</template>
<script>
import {
  devicesList,
  getDevicesCondition,
  createDevices,
  deleteDevices,
  getMemberCondition,
} from "@api/equipment.js";
export default {
  name: "equipment",
  data() {
    return {
      tableHeigth: document.body.clientHeight - 280,
      addModal: false,
      edit: true,
      params: {
        keywords: "",
        project_id: "",
        department_id: "",
        use_mid: "",
        status: "",
        current: 1,
        size: 10,
      },
      projectlist: [],
      departmentList: [],
      userlist: [],
      statelist: [],
      projectAddList: [],
      mobileAddList: [],
      departmentAddList: [],
      addUserlist: [],
      total: 0,
      pageOpts: [10, 20, 30, 40],
      columns: [
        {
          key: "id",
          title: "ID",
          width: 80,
        },
        {
          key: "phone_model",
          title: "手机型号",
          ellipsis: "true",
          tooltip: "true",
          minWidth: 100,
        },
        {
          key: "name",
          title: "名称",
          ellipsis: "true",
          tooltip: "true",
          minWidth: 100,
        },
        {
          slot: "sim_card",
          title: "手机号",
          width: 130,
        },
        {
          slot: "status_name",
          title: "状态",
          width: 80,
        },
        {
          key: "project_name",
          title: "项目",
          width: 100,
        },
        {
          key: "department_name",
          title: "部门",
          width: 180,
        },
        {
          key: "use_mname",
          title: "使用人",
          width: 90,
        },
        {
          key: "remark",
          title: "备注",
          ellipsis: "true",
          tooltip: "true",
          minWidth: 120,
        },
        {
          slot: "action",
          title: "操作",
          width: 110,
          fixed: "right",
        },
      ],
      list: [],
      loading: false,
      btnLoading: false,
      equipmentInfo: {
        id: "",
        phone_model: "",
        name: "",
        mobile: [],
        project_id: null,
        department_id: null,
        use_mid: "",
        use_mname: "",
        remark: "",
        status: true,
      },
      rules: {
        phone_model: [{ required: true, message: "请输入手机类型" }],
        name: [{ required: true, message: "请输入名称" }],
        department_id: [{ required: true, message: "请选择部门" }],
        project_id: [{ required: true, message: "请选择项目" }],
      },
    };
  },
  computed: {},
  mounted() {
    this.getData();
  },
  methods: {
    showAll(e) {
      if (e) {
        let downList = document.querySelectorAll(
          ".ivu-select-dropdown-list .ivu-select-item"
        );
        downList.forEach((item) => {
          item.style.display = "block";
        });
      }
    },
    spaceSelect(e) {
      if (e.length > 2) {
        this.$Message.warning("手机号最多可以选2个");
        e.pop();
      }
    },
    //切换page
    changePage(index) {
      this.params.current = index;
      this.getData();
    },
    changepageSize(val) {
      this.params.size = val;
      this.getData();
    },
    handleDel(info) {
      this.$Modal.confirm({
        title: "删除提示",
        content:
          "是否确认删除此条记录，删除后不可恢复<br>已绑定手机号：" +
          info.sim_card,
        onOk: () => {
          deleteDevices({ id: info.id })
            .then(() => {
              this.$Message.success("删除成功");
              this.getData();
            })
            .catch(() => {});
        },
      });
    },
    handleAdd() {
      getDevicesCondition({ devices_id: 0 }).then((res) => {
        this.mobileAddList = res.condition.scard_arr;
        this.projectAddList = res.condition.project_arr;
        this.departmentAddList = this.changeData(res.condition.department_arr);
        this.equipmentInfo = {
          id: "",
          phone_model: "",
          name: "",
          mobile: [],
          project_id: null,
          department_id: null,
          use_mid: "",
          use_mname: "",
          remark: "",
          status: true,
        };
        this.$nextTick(() => {
          this.$refs.create.resetFields();
        });
      });
      this.addModal = true;
      this.edit = true;
    },
    handleEdit(info) {
      this.addModal = true;
      this.edit = false;
      getDevicesCondition({ devices_id: info.id }).then((res) => {
        this.mobileAddList = res.condition.scard_arr;
        this.projectAddList = res.condition.project_arr;
        this.departmentAddList = this.changeData(res.condition.department_arr);
        this.equipmentInfo = {
          id: info.id,
          phone_model: info.phone_model,
          name: info.name,
          mobile: info.sim_card_id,
          project_id: info.project_id ? parseInt(info.project_id) : null,
          department_id: parseInt(info.department_id)
            ? parseInt(info.department_id)
            : null,
          use_mid: parseInt(info.use_mid),
          use_mname: info.use_mname,
          remark: info.remark,
          status: info.status == 1 ? true : false,
        };
        this.changeAddPro();
      });
    },
    changeData(data) {
      data.forEach((item) => {
        item.value = +item.id;
        item.title = item.department_name;
        item.expand = true;
        if (item.children && item.children.length > 0) {
          this.changeData(item.children);
        }
      });
      return data;
    },
    getData() {
      this.loading = true;
      const params = {
        keywords: this.params.keywords,
        project_id: this.params.project_id,
        department_id: this.params.department_id,
        use_mid: this.params.use_mid,
        status: this.params.status,
        pageSize: this.params.size,
        page: this.params.current,
      };
      devicesList(params)
        .then((res) => {
          this.list = res.list;
          this.total = res.total;
          this.projectlist = res.condition.project_arr;
          this.statelist = res.condition.status_arr;
          this.departmentList = this.changeData(res.condition.department_arr);
          this.userlist = res.condition.use_member_arr;
          this.loading = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    searchData() {
      this.params.current = 1;
      this.getData();
    },
    clearDep() {
      this.params.department_id = "";
      this.searchData();
    },
    changePro() {
      this.params.use_mid = "";
      this.userlist = [];
      this.getData();
      if (!this.params.project_id) {
        return;
      }
      getMemberCondition({ project_id: this.params.project_id }).then((res) => {
        this.userlist = res;
      });
    },
    findUser(id) {
      return this.addUserlist.findIndex((item) => {
        return item.value == id;
      });
    },
    changeAddPro() {
      getMemberCondition({
        project_id: this.equipmentInfo.project_id,
        department_id: this.equipmentInfo.department_id,
      }).then((res) => {
        this.addUserlist = res;
        if (this.findUser(this.equipmentInfo.use_mid) == -1) {
          this.equipmentInfo.use_mid = null;
          this.equipmentInfo.use_mname = "";
        }
      });
    },
    changeAddUser(e) {
      if (e) {
        this.equipmentInfo.use_mname = e.label;
      }
    },
    addPatient() {
      this.btnLoading = true;
      const params = {
        id: this.equipmentInfo.id,
        phone_model: this.equipmentInfo.phone_model,
        name: this.equipmentInfo.name,
        mobile: this.equipmentInfo.mobile.join(","),
        project_id: this.equipmentInfo.project_id,
        department_id: this.equipmentInfo.department_id,
        use_mid: this.equipmentInfo.use_mid,
        use_mname: this.equipmentInfo.use_mname,
        remark: this.equipmentInfo.remark,
        status: this.equipmentInfo.status ? 1 : 0,
      };
      if (this.edit) {
        createDevices(params)
          .then((res) => {
            this.$Message.success("新增成功");
            this.addModal = false;
            this.btnLoading = false;
            this.getData();
          })
          .catch(() => {
            this.btnLoading = false;
          });
      } else {
        createDevices(Object.assign({}, params, { id: this.equipmentInfo.id }))
          .then((res) => {
            this.$Message.success("编辑成功");
            this.addModal = false;
            this.btnLoading = false;
            this.getData();
          })
          .catch(() => {
            this.btnLoading = false;
          });
      }
    },
    ok() {
      this.$refs.create.validate((valid) => {
        if (valid) {
          this.addPatient();
        } else {
          this.addModal = true;
          // this.$Message.error('填写错误，保存失败！')
          return;
        }
      });
    },
  },
};
</script>
